# from django_filters import rest_framework as filters
import django_filters
from django.db.models import Q
from .models import Goods


class GoodsFilter(django_filters.rest_framework.FilterSet):
    # price_min = django_filters.NumberFilter(field_name='shop_price', lookup_expr='gte', label='最低价', help_text='大于等于')
    price_min = django_filters.NumberFilter(field_name='shop_price', lookup_expr='gte')
    price_max = django_filters.NumberFilter(field_name='shop_price', lookup_expr='lte', label='最高价', help_text='小于等于')
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')
    top_category = django_filters.NumberFilter(method='top_category_filter')

    def top_category_filter(self, queryset, name, value):
        return queryset.filter(Q(category_id=value) |
                               Q(category__parent_category_id=value) |
                               Q(category__parent_category__parent_category_id=value))

    class Meta:
        model = Goods
        fields = ["price_min", "price_max", "name", "is_hot"]
        # 按照下面的写法，过滤条件变成了没有指定字段的形式：
        # http://127.0.0.1:8000/goods/?shop_price__lte=200&shop_price__gte=100
        # fields = {'shop_price': ['lte', 'gte']}
